package com.geqian.web.serializer;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.TreeNode;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;

import java.io.IOException;

public class ConversionDeserializer extends JsonDeserializer<Object> implements ContextualDeserializer {

    private DeserializationConverter deserializerConverter;

    private BeanProperty beanProperty;


    @Override
    public JsonDeserializer<?> createContextual(DeserializationContext deserializationContext, BeanProperty property) throws JsonMappingException {
        try {

            this.beanProperty = property;
            Class<? extends DeserializationConverter> converter = property.getAnnotation(PropertyConverter.class).deserializationConverter();
            if (!converter.isAssignableFrom(DeserializationConverter.class)) {
                deserializerConverter = converter.getConstructor().newInstance();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return this;
    }

    @Override
    public Object deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        ObjectMapper objectMapper = (ObjectMapper) jsonParser.getCodec();
        TreeNode treeNode = objectMapper.readTree(jsonParser);
        try {
            return deserializerConverter.conversion(treeNode, beanProperty, objectMapper);
        } catch (Exception e) {
            return objectMapper.treeToValue(treeNode, beanProperty.getType().getRawClass());
        }
    }
}